package com.yipi.yupicturebackend.controller;

import com.yipi.yupicturebackend.common.BaseResponse;
import com.yipi.yupicturebackend.common.ResultUtils;
import com.yipi.yupicturebackend.entity.User;
import com.yipi.yupicturebackend.exception.ErrorCode;
import com.yipi.yupicturebackend.exception.ThrowUtils;
import com.yipi.yupicturebackend.model.DTO.user.UserRegisterRequest;
import com.yipi.yupicturebackend.model.DTO.user.UserloginRequest;
import com.yipi.yupicturebackend.model.VO.LoginUserVO;
import com.yipi.yupicturebackend.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassward = userRegisterRequest.getUserPassword();
        String checkPassward = userRegisterRequest.getCheckPassword();
        long userId = userService.UserRegister(userAccount, userPassward, checkPassward);
        return ResultUtils.success(userId);
    }

    /**
     * 用户登录
     * @param userloginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserloginRequest userloginRequest, HttpServletRequest request){
        ThrowUtils.throwIf(userloginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userloginRequest.getUserAccount();
        String userPassward = userloginRequest.getUserPassword();
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassward, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 获取当前登录用户
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(userService.getLoginUserVO(loginUser));
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request){
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean b = userService.userLogout(request);
        return ResultUtils.success(b);
    }
}
